//
//  Vector3.hpp
//  math3d
//
//  Created by 姚或 on 2021/1/29.
//

#ifndef Vector3_h
#define Vector3_h

#include <math.h>

struct Vector3
{
    typedef float   real_type;
    real_type x, y, z;
    Vector3() {}
    Vector3(const Vector3 &a): x(a.x), y(a.y), z(a.z) {}
    Vector3(real_type nx, real_type ny, real_type nz): x(nx), y(ny), z(nz) {}

    Vector3 &operator=(const Vector3 &a)
    {
        x = a.x;
        y = a.y;
        z = a.z;
        return *this;
    }

    bool operator==(const Vector3 &a)
    {
        return x == a.x && y == a.y && z == a.z;
    }

    bool operator!=(const Vector3 &a)
    {
        return x != a.x || y != a.y || z != a.z;
    }

    Vector3 &zero()
    {
        x = y = z = 0;
        return *this;
    }

    Vector3 operator-()const
    {
        return Vector3(-x, -y, -z);
    }

    Vector3 operator+(const Vector3 &a) const
    {
        return Vector3(x + a.x, y + a.y, z + a.z);
    }

    Vector3 operator-(const Vector3 &a) const
    {
        return Vector3(x - a.x, y - a.y, z - a.z);
    }

    Vector3 operator*(real_type k) const
    {
        return Vector3(x * k, y * k, z * k);
    }

    Vector3 operator/(real_type k) const
    {
        auto k1 = 1 / k;
        return operator*(k1);
    }

    Vector3 &operator+=(const Vector3 &a)
    {
        x += a.x;
        y += a.y;
        z += a.z;
        return *this;
    }
    Vector3 &operator-=(const Vector3 &a)
    {
        x -= a.x;
        y -= a.y;
        z -= a.z;
        return *this;
    }
    Vector3 &operator*=(real_type k)
    {
        x *= k;
        y *= k;
        z *= k;
        return *this;
    }
    Vector3 &operator/=(real_type k)
    {
        k = 1.0 / k;
        return operator*=(k);
    }

    Vector3 &normalize()
    {
        float magSq = x * x + y * y + z * z;
        if(magSq > 0)
        {
            return operator/=(sqrt(magSq));
        }
        return zero();
    }

    real_type operator*(const Vector3 &a)const
    {
        return x * a.x + y * a.y + z * a.z;
    }
};

inline Vector3::real_type vectorMag(const Vector3 &a)
{
    return sqrt(a.x * a.x + a.y * a.y + a.z * a.z);
}

inline Vector3 cross(const Vector3 &a, const Vector3 &b)
{
    return Vector3(
               a.y * b.z - a.z * b.y,
               a.z * b.x - a.x * b.z,
               a.x * b.y - a.y * b.x
           );
}

inline Vector3::real_type distance(const Vector3 &a, const Vector3 &b)
{
    auto dx = a.x - b.x;
    auto dy = a.y - b.y;
    auto dz = a.z - b.z;
    return sqrt(dx * dx + dy * dy + dz * dz);
}

extern const Vector3 kZeroVector3;
#endif /* Vector3_h */
